﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using MiniErp.Entity.DataStreams.DOs;
using MiniErp.Entity.DataStreams.DTOs;
using MiniErp.Entity.DataStreams.DTOs.Users;
using MiniErp.Entity.JWTs;
using MiniErp.Service.JWTService.IService;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MiniErp.Service.JWTService.Service
{
    public class TokenService : ITokenService
    {
        private readonly JWTTokenOPotions _tokens;
        private readonly IHttpContextAccessor _httpContext;
        public TokenService(IOptionsMonitor<JWTTokenOPotions> tokens, IHttpContextAccessor httpContext)
        {
            _tokens = tokens.CurrentValue;
            _httpContext = httpContext;
        }

        public string GetRightName()
        {
            var rightName = _httpContext.HttpContext.User.FindFirst(item => item.Type == "RightName").Value;
            return rightName;
        }
        public int GetUId()
        {
            var uId = _httpContext.HttpContext.User.FindFirst(item => item.Type == "UId").Value;
            return Convert.ToInt32(uId);
        }
        public string GetUserName()
        {
            var uId = _httpContext.HttpContext.User.FindFirst(item => item.Type == "UserName").Value;
            return uId;
        }
        public string GetToken(UserDTO users)
        {
            //存入Token的信息
            var claims = new[] {
                new Claim(ClaimsModel.UId,users.UId.ToString()),
                new Claim(ClaimsModel.UserName,users.UserName),
                new Claim(ClaimsModel.JobsId,users.JobsId.ToString())
            };
            //加密key
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokens.SecurityKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //生成Token
            JwtSecurityToken token = new JwtSecurityToken(
                issuer: _tokens.Issuer,
                audience: _tokens.Audience,
                claims: claims,
                expires: DateTime.Now.AddDays(14),
                signingCredentials: creds);
            //将Token信息转换为字符串
            var returnToken = new JwtSecurityTokenHandler().WriteToken(token);
            return returnToken;
        }


    }
}
